package com.jeecg.school.controller;
import com.jeecg.school.Util.RequestUtil;
import com.jeecg.school.entity.GradeEntity;
import com.jeecg.school.entity.StudentEntity;
import com.jeecg.school.entity.TeacherEntity;
import com.jeecg.school.service.GradeServiceI;
import com.jeecg.school.service.StudentServiceI;
import com.jeecg.school.service.TeacherServiceI;

import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.hibernate.qbc.PagerUtil;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.PasswordUtil;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;


/**   
 * @Title: Controller  
 * @Description: 学生表
 * @author onlineGenerator
 * @date 2020-02-05 12:43:04
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/studentController")
public class StudentController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

	@Autowired
	private StudentServiceI studentService;
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private GradeServiceI gradeService;
	
	@Autowired
	private TeacherServiceI teacherService;

	/**
	 * 学生表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("school/studentList");
	}

	/**
	 * 学生个人信息页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "person")
	public ModelAndView person(HttpServletRequest request) {
		TSUser user = ResourceUtil.getSessionUser();
		StudentEntity student = studentService.getEntity(StudentEntity.class, user.getId());
		if(student.getGradId() != null) {
			GradeEntity grade = gradeService.getEntity(GradeEntity.class, student.getGradId());
			request.setAttribute("gradePage", grade);
			if(grade.getTeacherId() != null) {
				TeacherEntity teacher = teacherService.getEntity(TeacherEntity.class, grade.getTeacherId());
				request.setAttribute("teacherPage", teacher);
			}
		}
		request.setAttribute("studentPage", student); 
		return new ModelAndView("school/student-person");
	}
	
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(StudentEntity student,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(StudentEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, student, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		String loginSign = ResourceUtil.getSessionLoginSign();
		if(loginSign.equals("3")) {
			this.studentService.getDataGridReturn(cq, true);
		} else {
			TSUser user = ResourceUtil.getSessionUser();
			Map<String, String> param = RequestUtil.getParameterMap(request);
			param.put("teacherId", user.getId());
			
			int allCounts = 0;
			List<StudentEntity> studentList = null;
			try {
				allCounts = this.studentService.getStudentCountByTeacher(param);
				int pageSize = cq.getPageSize();/*每页显示数*/
			    int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),pageSize);// 当前页
			    param.put("curPageNO", String.valueOf(curPageNO));
			    param.put("pageSize", String.valueOf(pageSize));
			    studentList = this.studentService.queryListByTeacher(param);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			cq.getDataGrid().setResults(studentList);
	        cq.getDataGrid().setTotal(allCounts);
		}
		
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除学生表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(StudentEntity student, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		student = systemService.getEntity(StudentEntity.class, student.getId());
		message = "学生表删除成功";
		try{
			studentService.delete(student);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "学生表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除学生表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "学生表删除成功";
		try{
			for(String id:ids.split(",")){
				StudentEntity student = systemService.getEntity(StudentEntity.class, 
				id
				);
				studentService.delete(student);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "学生表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加学生表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(StudentEntity student, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "学生表添加成功";
		String password = PasswordUtil.encrypt(student.getStuNo(),"123456", PasswordUtil.getStaticSalt());
		student.setPassword(password);
		try{
			studentService.save(student);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "学生表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新学生表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(StudentEntity student, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "学生表更新成功";
		StudentEntity t = studentService.get(StudentEntity.class, student.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(student, t);
			studentService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "学生表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 *  修改学生密码
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doChangePaword")
	@ResponseBody
	public AjaxJson doChangePaword(StudentEntity student, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "修改密码成功";
		StudentEntity t = studentService.get(StudentEntity.class, student.getId());
		String password = PasswordUtil.encrypt(t.getStuNo(),student.getPassword(), PasswordUtil.getStaticSalt());
		student.setPassword(password);
		try {
			MyBeanUtils.copyBeanNotNull2Bean(student, t);
			studentService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "修改密码失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 学生表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(StudentEntity student, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(student.getId())) {
			student = studentService.getEntity(StudentEntity.class, student.getId());
			req.setAttribute("studentPage", student);
		}
		return new ModelAndView("school/student-add");
	}
	/**
	 * 学生表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(StudentEntity student, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(student.getId())) {
			student = studentService.getEntity(StudentEntity.class, student.getId());
			req.setAttribute("studentPage", student);

			if(StringUtil.isNotEmpty(student.getGradId())){
				GradeEntity grade = gradeService.getEntity(GradeEntity.class, student.getGradId());
				req.setAttribute("gradePage", grade);
			}
		}
		return new ModelAndView("school/student-update");
	}
	
	/**
	 *  修改学生密码
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "goChangePaword")
	public ModelAndView goChangePaword(String id,HttpServletRequest request) {
		request.setAttribute("id", id);
		if (StringUtil.isNotEmpty(id)) {
			StudentEntity student = studentService.getEntity(StudentEntity.class, id);
			request.setAttribute("studentPage", student);
		}
		return new ModelAndView("school/student-changePaword");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","studentController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(StudentEntity student,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(StudentEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, student, request.getParameterMap());
		List<StudentEntity> students = this.studentService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"学生表");
		modelMap.put(NormalExcelConstants.CLASS,StudentEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("学生表列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,students);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(StudentEntity student,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"学生表");
    	modelMap.put(NormalExcelConstants.CLASS,StudentEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("学生表列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<StudentEntity> listStudentEntitys = ExcelImportUtil.importExcel(file.getInputStream(),StudentEntity.class,params);
				for (StudentEntity student : listStudentEntitys) {
					studentService.save(student);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
}
